<template>
  <div o-Container>
    <o-item v-bind:source="item.datasource" v-bind="{loaded:load,backed:back}"></o-item>
    <o-list v-bind:source="list.datacolumn" v-bind="{modified:modify}"/>
    <!-- 数据源修改记录 -->
    <o-list v-bind:source="list.datasourcehis" v-bind="{modified:modifySourceHis}"/>
    <o-dialog v-bind:source="panel.structure" v-bind="{opened:load,closed:load}">
      <template slot="content">
        <el-button type="info" v-on:click="closeCode" size="mini" style="margin: 0 0 3px 0">Back</el-button>
        <el-input v-model="structureData" placeholder="架构代码" v-bind="{type:'textarea',rows:20}"></el-input>
      </template>
    </o-dialog>
    <o-dialog v-bind:source="panel.history">
      <template slot="content">
        <o-item v-bind:source="item.datasourcehis" v-bind="{backed:backHis}"></o-item>
      </template>
    </o-dialog>
  </div>
</template>

<script>
  export default {
    name: "mms_engine_datasource_item", /* 这个name暂时不知道用啥用，根据官方文档说的是方便排错的 */
    data() {
      return {
        octopus: this.$parent.octopus,
        item: {
          datasource: {
            // 以下参数默认由组件内部创建，但是如果有需要，开发人员可在这里提前设置，组件将按照您的预期渲染。
            // cache: false,
            // control: null,
            // dataExtend: null,
            data: {
              id: 19,
              value: "#{param=id}",
              cellData: [
                {name: "DatabaseID", link: [{mapping: "TypeID", value: 1}, {mapping: "Enable", value: 1}]},
                {name: "Name"},
                {name: "PrimaryKey"},
                {name: "OrderData"},
                {name: "ParentKey"},
                {name: "ParentValue"},
                {name: "ListSize"},
                {name: "RowSize"},
                {name: "Width"},
                {name: "Height"},
                {name: "IsPartition"},
                {name: "PartitionColumn"},
                {name: "PartitionType"},
                {name: "Performance"},
                {name: "CreateDate"},
                {name: "CreatorID"},
                {name: "UpdateDate"},
                {name: "UpdaterID"},
                {name: "Query"},
                {name: "Note"}]
            },
            // 自定义button按钮，开发者选项。
            button: [{class: "success", click: this.save, text: "Save"},
              {class: "warning", click: this.refresh, text: "Refresh"},
              {class: "primary", click: this.structure, text: "Structure"}]
          },
          // 数据源历史
          datasourcehis: {
            data: {
              id: 1066, // 八爪鱼ID
              cellData: [
                {name: "TableID"},	// 所属数据源
                {name: "UpdateDate"},	// UpdateDate
                {name: "UpdaterID"},	// UpdaterID
                {name: "CreateDate"},	// CreateDate
                {name: "Query"},	// 脚本
              ],
              height: "300px"
            }
          }
        },
        list: {
          datacolumn: {
            data: {
              id: 20, // 八爪鱼ID
              cellData: [
                {name: "TableID", filterKey: "=", show: false},
                {name: "LanguageID", width: 170},
                {name: "Name", searchKey: "Like", width: 200},
                // {name: "Width"},
                // {name: "Height"},
                // {name: "LanguageID"},
                {name: "ControlTypeID", searchKey: "="},
                {name: "ControlSourceID", width: 170, searchKey: "="},
                {name: "ControlSourceText", width: 80},
                {name: "ControlSourceValue", width: 80},
                {name: "ControlSourceParentKey", width: 60},
                {name: "ControlSourceParentValue", width: 60},
                {name: "IsNull", width: 60, searchKey: "="},
                {name: "IsDisabled", width: 60, searchKey: "="},
                {name: "IsEncryption", width: 60},
                {name: "IsHierarchy", width: 60},
                {name: "DefaultValue"},
                {name: "Note"},
                {name: "CreateDate", width: 160},
              ],
              height: "300px"
            }
          },
          // 数据源历史
          datasourcehis: {
            data: {
              id: 1066, // 八爪鱼ID
              cellData: [
                {name: "TableID", show: false, filterKey: "="},	// 所属数据源
                {name: "UpdateDate", width: 160, searchKey: "BETWEEN"},	// UpdateDate
                {name: "UpdaterID", searchKey: "=", width: 100},	// UpdaterID
                {name: "Query", searchKey: "LIKE", width: 1700},	// 脚本
              ],
              height: "300px"
            }
          }
        },
        panel: {
          structure: {
            visible: false,
          },
          history: {
            visible: false,
          }
        },
        structureData: "",
      }
    },
    created: function () {
      // this.init();
    },
    activated: function () {
      this.init();
    },
    methods: {
      init: function () {
        // alert(this.octopus.passport.id);

        let param = this.octopus.router.get().query;
        if (param["id"] != null) {
          let sourceID = param["id"];
          this.octopus.tools.parseCell(this.list.datasourcehis.data, "TableID").filterValue = sourceID;
        }
      },
      load: function () {
        // 得到TableID对象
        let ListFilterData = $.grep(this.list.datacolumn.data.cellData, function (value) {
          return value.name == "TableID";//筛选出语言ID编号
        })[0];
        // 如果Menu有主键值，说明是更新动作，否则创建动作，没有的加了也白加。
        if (this.item.datasource.data.value) {
          // 定义TableID具体内容
          ListFilterData.filterValue = this.item.datasource.data.value;
        } else {
          // 新创建页面时默认-1，查不到，最牛逼。
          ListFilterData.filterValue = -1;
        }
        this.list.datacolumn.control.load();


        // 更新最新更新人
        // this.octopus.tools.parseCell(this.item.datasource.data, "UpdateDate").defaultValue =  this.octopus.tools.date("yyyy-MM-dd HH:mm:ss");
        // this.octopus.tools.parseCell(this.item.datasource.data, "UpdaterID").defaultValue =  this.octopus.passport.id.toString();
      },
      // 保存后回调事件，主控件为主的，子控件依赖主控件的，可在主控件保存后调用子控件的save。
      // 回调时因为数据是全部钩子动态绑定的，唯独因为创建会把保存类型给冲掉，所以这样要回传保存的类型
      save: function (data) { //保存
        // if (data.status.code == 200) {
        //   this.octopus.tips.success("[" + data.status.code + "] 数据保存成功，准备开始读取八爪鱼源表架构。");
        // } else {
        //   this.octopus.tips.error(data);
        // }

        this.octopus.tools.parseCell(this.item.datasource.data, "UpdateDate").defaultValue = this.octopus.tools.date("yyyy-MM-dd HH:mm:ss");
        this.octopus.tools.parseCell(this.item.datasource.data, "UpdaterID").defaultValue = this.octopus.passport.id.toString();
        this.item.datasource.control.save();
        this.saveQueryHisData(this.item.datasource.data);

        this.octopus.tips.success("数据保存成功。");
      },
      // 保存插入历史记录表，当Item表保存完毕以后。
      saveQueryHisData: function (data) {
        let o = this;
        let TableID = this.octopus.tools.parseCell(data, "ID").defaultValue;
        let TableQuery = this.octopus.tools.parseCell(data, "Query").defaultValue;
        let UpdateDate = this.octopus.tools.parseCell(data, "UpdateDate").defaultValue;
        let UpdaterID = this.octopus.tools.parseCell(data, "UpdaterID").defaultValue;
        // alert(TableID + "," + TableQuery + "," + UpdateDate + "," + UpdaterID);
        // console.warn(JSON.stringify(data));

        // 更新QMS操作日志
        this.octopus.request.api.post("/Octopus/Engine/Item", {
            id: 1066, // 质量-需求事件表
            type: "CREATE",
            cellData: [
              {name: "TableID", defaultValue: TableID},
              {name: "Query", defaultValue: TableQuery},
              {name: "UpdateDate", defaultValue: UpdateDate},
              {name: "UpdaterID", defaultValue: UpdaterID},
            ],
          },
          // 处理回调事件，通过分析data.status.code的状态来实现。
          function (event_data) {
            if (event_data.status.code == 200) {
              //
              //   o.octopus.tips.success("[" + event_data.status.code + "] Data Save Success.");
              //   o.list.requirement.control.load();
              // } else {
              //   o.octopus.tips.error(event_data);

              o.list.datasourcehis.control.load();
            }
          });
      },
      // 根据数据源刷新表结构，同时更新缓存。
      refresh: function () {
        let o = this; //保存this
        this.octopus.request.api.post("/Octopus/Engine/Refresh", {
            type: "OCTOPUS",
            id: this.item.datasource.data.value //id赋值
          },
          // 处理回调事件，通过分析data.status.code的状态来实现。
          function (data) {
            if (data.status.code == 200) {
              // 刷新源表列架构List控件，完美！！！！！
              o.load();
              o.octopus.tips.success("[" + data.status.code + "] 源表架构保存成功。");
            } else {
              o.octopus.tips.error(data);
            }
          });
      },
      // 快速生成架构
      structure: function () {
        this.panel.structure.visible = true;

        this.structureData = "";
        this.structureData += "cellData: [";
        // {name: "BuildingID", width: 100, filterKey: "=",show: false}, //项目
        // {name:"PanoramaID", width: 160, searchKey: "like"},//名称

        if (this.list.datacolumn.data) {
          // console.log(this.list.datacolumn.data.queryData);

          // this.list.datacolumn.data.queryData.each(function (index, item) {
          //   this.structureData += "\n " + item.Name;
          // });

          this.list.datacolumn.data.queryData.map(item => {
            this.structureData += "\n\t{name: \"" + item.Name + "\"},\t// " + item.LanguageID;
          })
        }
        this.structureData += "\n],";
      },
      back: function () {
        this.octopus.router.jump("/MMS/Engine/Datasource/List");
      },
      backHis: function () {
        this.panel.history.visible = false;
      },
      modify: function (row) {
        this.octopus.router.jump("/MMS/Engine/Datacolumn/Modify?id=" + row.ID);
      },
      modifySourceHis: function (row) {
        this.item.datasourcehis.data.value = row.ID;
        this.item.datasourcehis.control.load();//编辑根据行id请求数据；然后加载
        this.panel.history.visible = true;
      },
      closeCode: function () {
        //
        this.panel.structure.visible = false;
      },
    },
    props: ["oData"]
  }
</script>
